package com.hula.onion.book.server.spider.platforms.jinlianchu;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/26.
 */
@Component
public class JinLianChuSpiderHelper {
    private static final Logger logger = LoggerFactory.getLogger(JinLianChuSpiderHelper.class);

    public Map<String, Object> installRequestParams(LoginForm loginForm) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("phone", loginForm.getUserName());
        map.put("password", loginForm.getPassword());
        return map;
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {
        if (StringUtils.isEmpty(html)) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
        try {
            Document document = Jsoup.parse(html);
            Element el = document.select("div.mb_money").first();
            Elements els = el.getAllElements();
            String amount = els.get(4).text();
            //收益隐藏部分html解析
            /*
               <div class="money_hide">
                            可用余额：0.00元<br />
                            待收本金：0.00元<br />
                            待收收益：0.00元<br />
                            提现处理中金额：0.00元<br />
                            <!-- 续投冻结金额：0.00元-->
                 </div>
             */
            Element wIEl = document.selectFirst("div.money_hide");
            Element wIEls = wIEl.getAllElements().get(0);
            String[] strs = StringUtils.split(wIEls.html(), "<br>");
            String[] wis = StringUtils.split(strs[2], "：");
            String waitIntrest = StringUtils.remove(wis[1], "元").trim();
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setAmount(new BigDecimal(amount));
            accountInfo.setWaitIntrest(new BigDecimal(waitIntrest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            logger.error("[JinLianChuSpiderHelper] parseAccountBalance fail!", e);
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
